package com.rupeng.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.pojo.Classes;
import com.rupeng.pojo.Subject;
import com.rupeng.service.ClassesService;
import com.rupeng.service.SubjectService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;

@Controller
@RequestMapping("/classes")
public class ClassesController {
	@Autowired
	private ClassesService classesService;
	@Autowired
	private SubjectService subjectService;
	@RequestMapping("/list.do")
	public ModelAndView list() {
		ModelAndView modelAndView = new ModelAndView("classes/list");
		List<Classes> classesList = classesService.selectList();
		List<Subject> subjects = subjectService.selectList();
		modelAndView.addObject("classesList", classesList);
		modelAndView.addObject("subjects", subjects);
		return modelAndView;
	}
	@RequestMapping(value="/add.do",method=RequestMethod.GET)
	public ModelAndView addPage() {
		List<Subject> subjects = subjectService.selectList();
		return new ModelAndView("classes/add", "subjects", subjects);
	}
	@RequestMapping(value="/add.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult addSubmit(String name, Long subjectId) {
		if (CommonUtils.isEmpty(name) || subjectId==null) {
			return AjaxResult.errorInstance("表单不完整");
		}
		Classes classes = new Classes();
		classes.setName(name);
		classes.setSubjectId(subjectId);
		classesService.insert(classes);
		return AjaxResult.successInstance("新建班级成功");
	}
	@RequestMapping(value="/delete.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult delete(Long id) {
		classesService.delete(id);
		return AjaxResult.successInstance("删除成功");
	}
	@RequestMapping(value="/update.do",method=RequestMethod.GET)
	public ModelAndView updatePage(Long id) {
		ModelAndView modelAndView = new ModelAndView("classes/update");
		Classes classes = classesService.selectOne(id);
		List<Subject> subjects = subjectService.selectList();
		modelAndView.addObject("classes", classes);
		modelAndView.addObject("subjects", subjects);
		return modelAndView;
	}
	@RequestMapping(value="/update.do",method=RequestMethod.POST)
	public @ResponseBody AjaxResult updateSubmit(Long id, String name, Long subjectId) {
		if (id==null || CommonUtils.isEmpty(name) || subjectId==null) {
			return AjaxResult.errorInstance("表单不完整");
		}
		Classes classes = new Classes();
		classes.setId(id);
		classes.setName(name);
		classes.setSubjectId(subjectId);
		classesService.update(classes);
		return AjaxResult.successInstance("班级信息更改成功");
	}
}
